//
//  Background.m
//  TheifRunning
//
//  Created by Lion on 6/16/14.
//  Copyright (c) 2014 Apportable. All rights reserved.
//

#import "Background.h"

@implementation Background{
    CCPhysicsNode *_physicBg;
    CGFloat scrollSpeed;

    CCNode *_normalTree2;
    CCNode *_normalTree3;
    CCNode *_normalTree4;
    CCNode *_normalTree5;
    
    NSArray *_normalTrees;
}
@synthesize normalTree1;

#define ARC4RANDOM_MAX      0x100000000
// visibility on a 3,5-inch iPhone ends a 88 points and we want some meat
static const CGFloat minimumXPosition = 0;
// visibility ends at 480 and we want some meat
static const CGFloat maximumXPosition = 200;

static const CGFloat minimumYPosition = 0;
static const CGFloat maximumYPosition = 15;

- (void) didLoadFromCCB{
    scrollSpeed = 35;
    //adding ground array
    _normalTrees = @[normalTree1, _normalTree2, _normalTree3, _normalTree4, _normalTree5];
    normalTree1.physicsBody.collisionType = @"tree";
    for (CCNode *tree in _normalTrees) {
        tree.zOrder = 0;
    }
}

- (void) update:(CCTime)delta{
    scrollSpeed += delta*10;
    // loop the ground
    for (CCNode *tree in _normalTrees) {
        // get the world position of the ground
        CGPoint treeWorldPosition = [_physicBg convertToWorldSpace:tree.position];
        // get the screen position of the ground
        CGPoint treeScreenPosition = [self convertToNodeSpace:treeWorldPosition];
        // if the left corner is one complete width off the screen, move it to the right
        if (treeScreenPosition.x <= (-1 * tree.contentSize.width)) {
            // value between 0.f and 1.f
            CGFloat random = ((double)arc4random() / ARC4RANDOM_MAX);
            CGFloat rangeX = maximumXPosition - minimumXPosition;
            
            CGFloat rangeY = maximumYPosition - minimumYPosition;
            tree.position = ccp(-_physicBg.position.x + 580 + (random * rangeX), 80 - (random * rangeY));
        }
    }
    
    //physicNode
    _physicBg.position = ccp(_physicBg.position.x - (scrollSpeed *delta), _physicBg.position.y);
}

@end
